﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.SessionState;
using System.Drawing;
using System.ComponentModel;
using System.IO;
using System.Drawing.Imaging;
public partial class CheckCode : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        CurrentAccount.SetValidateCode(GenerateCheckCode());
        this.CreateCheckCodeImage(GenerateCheckCode());
       
    }

    private string GenerateCheckCode()
    {
        Random rdm = new Random();

        int n = rdm.Next(0, 10000);

        string code = n.ToString("D4");
        Response.Cookies.Add(new HttpCookie("CheckCode", code));

        return code;
    }

    private void CreateCheckCodeImage(string checkCode)
    {
        int width = (int)(checkCode.Length * 11.5);
        Bitmap image = new Bitmap(width, 0x14);
        Graphics graphics = Graphics.FromImage(image);
        try
        {



            //生成随机生成器
            Random random = new Random();

            //清空图片背景色
            graphics.Clear(Color.WhiteSmoke);

            //画图片的背景噪音线
            for (int i = 0; i < 5; i++)
            {
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);

                graphics.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }

            graphics.DrawString(checkCode, new Font("Arial", 14f, FontStyle.Regular), new SolidBrush(Color.Red), (float)0f, (float)0f);
            MemoryStream stream = new MemoryStream();
            image.Save(stream, ImageFormat.Png);
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.ContentType = "image/png";
            HttpContext.Current.Response.BinaryWrite(stream.ToArray());

            HttpContext.Current.Response.End();
        }
        finally
        {
            graphics.Dispose();
            image.Dispose();
        }

    }
}
